import 'package:enterprise_v6_app/app/components/custom_app_bar.dart';
import 'package:enterprise_v6_app/app/components/dialing_function.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/ext/widget_extension.dart';
import 'package:enterprise_v6_app/app/core/utils/user_manager.dart';
import 'package:enterprise_v6_app/app/modules/task/task_all/security_all_fundamentals_page/clock_in/clock_in_controller.dart';
import 'package:enterprise_v6_app/router/app_pages.dart';

/// 我的任务-打卡
class ClockInControllerPage extends StatelessWidget {
  ClockInControllerPage({super.key});

  final controller = Get.put(ClockInController());

  @override
  Widget build(BuildContext context) {
    // 获取当天打卡列表
    controller.getDailyPlan();
    return GetBuilder(
      init: controller,
      builder: (_) {
        return Scaffold(
          backgroundColor: AppColors.bg_color_grey,
          appBar: CustomAppBar(
            titleText: '打卡',
            showAlarmButton: false,
          ),
          body: Container(
            padding: EdgeInsets.symmetric(horizontal: 14.w, vertical: 12.w),
            child: Column(
              children: [
                Container(
                  padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 14.w),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(8.w)),
                  ),
                  child: Row(
                    children: [
                      SvgPicture.asset(
                        AppImages.icon_home_default_avatar,
                        height: 40.w,
                        width: 40.w,
                      ),
                      AppGaps.hGap10,
                      Expanded(
                          child: Text(
                        UserManager.getUser()?.systemUser?.nickname ?? '',
                        style: TextStyle(
                          fontSize: 14.sp,
                          height: 1.2,
                          fontWeight: FontWeight.w400,
                          color: const Color(0xff495061),
                        ),
                      )),
                      Row(
                        children: [
                          Text(
                            '值班表',
                            style: TextStyle(
                              fontSize: 14.sp,
                              height: 1.2,
                              fontWeight: FontWeight.w400,
                              color: const Color(0xff495061),
                            ),
                          ),
                          AppGaps.hGap6,
                          SvgPicture.asset(
                            AppImages.icon_work_ledger,
                            height: 16.w,
                            width: 16.w,
                          ),
                        ],
                      ).clickOnce(() {
                        Get.toNamed(AppRoutes.schedulingPlan);
                      })
                    ],
                  ),
                ),
                AppGaps.vGap16,
                controller.currentPlan.id.isNotEmpty
                    ? Expanded(
                        child: Container(
                        padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 16.w),
                        decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.all(Radius.circular(8.w)),
                        ),
                        child: Column(
                          children: [
                            // 当日排班计划表
                            _getDailyScheduling(),
                            // 打卡信息
                            _getClockInRecords(),
                            AppGaps.vGap16,
                            // 领导及请假按钮
                            _getLeaderSLeave(),
                            // 打卡操作
                            Expanded(child: _getClockIn()),
                          ],
                        ),
                      ))
                    : Expanded(
                        child: Container(
                        alignment: Alignment.center,
                        padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 16.w),
                        decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.all(Radius.circular(8.w)),
                        ),
                        child: Text(
                          '当日暂无排班计划',
                          style: TextStyle(
                            fontSize: 16.sp,
                            height: 1.2,
                            fontWeight: FontWeight.w400,
                            color: const Color(0xff495061),
                          ),
                        ),
                      )),
                AppGaps.vGap32,
              ],
            ),
          ),
        );
      },
    );
  }

  /// 当日排班计划
  Widget _getDailyScheduling() {
    return Container(
      margin: EdgeInsets.only(bottom: 10.w),
      alignment: Alignment.center,
      height: 30.w,
      child: ListView.separated(
        scrollDirection: Axis.horizontal, // 设置为横向滚动
        itemCount: controller.planList.length,
        itemBuilder: (context, index) {
          final item = controller.planList[index];
          final bool isSelected = item.id == controller.currentPlan.id;
          return Container(
            alignment: Alignment.center,
            padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.w),
            decoration: BoxDecoration(
              color: isSelected ? const Color(0xffD4D9FF) : const Color(0xffF5F6F7),
              borderRadius: BorderRadius.circular(4.w),
            ),
            child: Text(
              item.classesName,
              style: TextStyle(
                fontSize: 12.sp,
                height: 1.2,
                fontWeight: FontWeight.w400,
                color: const Color(0xff495061),
              ),
            ),
          ).clickOnce(() {
            controller.selectPlan(item);
          });
        },
        separatorBuilder: (BuildContext context, int index) {
          return AppGaps.hGap20;
        },
      ),
    );
  }

  /// 获取打卡记录
  Widget _getClockInRecords() {
    // 班次开始与结束时间
    // 只显示时分
    String startTime = controller.currentPlan.classesBeginDate.split(' ')[1];
    startTime = startTime.substring(0, startTime.length - 3);
    String endTime = controller.currentPlan.classesEndDate.split(' ')[1];
    endTime = endTime.substring(0, endTime.length - 3);

    // 实际打卡时间
    // 上班时间
    String? checkInStartTime;
    // 结束时间
    String? checkInEndTime;
    if (controller.currentPlan.classesBeginDateRecord.isNotEmpty) {
      checkInStartTime = controller.currentPlan.classesBeginDateRecord.split(' ')[1];
      checkInStartTime = checkInStartTime.substring(0, checkInStartTime.length - 3);
    }
    if (controller.currentPlan.classesEndDateRecord.isNotEmpty) {
      checkInEndTime = controller.currentPlan.classesEndDateRecord.split(' ')[1];
      checkInEndTime = checkInEndTime.substring(0, checkInEndTime.length - 3);
    }

    return Row(
      children: [
        _getCheckIn(planTime: '上班$startTime', recordTime: checkInStartTime),
        AppGaps.hGap10,
        _getCheckIn(planTime: '下班$endTime', recordTime: checkInEndTime),
      ],
    );
  }

  /// 获取打卡信息展示
  Widget _getCheckIn({required String planTime, String? recordTime}) {
    return Expanded(
      child: Container(
        alignment: Alignment.topLeft,
        padding: EdgeInsets.symmetric(horizontal: 10.w, vertical: 5.w),
        decoration: BoxDecoration(
          color: const Color(0xffF5F6F7),
          borderRadius: BorderRadius.all(Radius.circular(4.w)),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              planTime,
              style: TextStyle(
                fontSize: 14.sp,
                height: 1.2,
                fontWeight: FontWeight.w400,
                color: const Color(0xff495061),
              ),
            ),
            AppGaps.vGap6,
            recordTime != null
                ? Row(
                    children: [
                      SvgPicture.asset(
                        AppImages.icon_screen_checkbox,
                        height: 12.w,
                        width: 12.w,
                      ),
                      AppGaps.hGap2,
                      Text(
                        '$recordTime 已打卡',
                        style: TextStyle(
                          fontSize: 12.sp,
                          height: 1.2,
                          fontWeight: FontWeight.w400,
                          color: const Color(0xffA0A7B5),
                        ),
                      )
                    ],
                  )
                : Text(
                    '未打卡',
                    style: TextStyle(
                      fontSize: 12.sp,
                      height: 1.2,
                      fontWeight: FontWeight.w400,
                      color: const Color(0xffA0A7B5),
                    ),
                  ),
          ],
        ),
      ),
    );
  }

  /// 获取值班领导信息及打卡
  Widget _getLeaderSLeave() {
    // 联系方式
    final List<String> phoneList = [];
    if (controller.currentPlan.onDutyLeaderTel.isNotEmpty) {
      phoneList.add(controller.currentPlan.onDutyLeaderTel);
    }
    if (controller.currentPlan.onDutyUserPhone.isNotEmpty) {
      phoneList.add(controller.currentPlan.onDutyUserPhone);
    }
    return Container(
      alignment: Alignment.topLeft,
      padding: EdgeInsets.symmetric(horizontal: 14.w, vertical: 12.w),
      decoration: BoxDecoration(
        color: const Color(0xffF2F4FF),
        borderRadius: BorderRadius.all(Radius.circular(4.w)),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '值班领导：${controller.currentPlan.onDutyLeader}',
            style: TextStyle(
              fontSize: 14.sp,
              height: 1.2,
              fontWeight: FontWeight.w400,
              color: const Color(0xff495061),
            ),
          ),
          AppGaps.vGap6,
          Row(
            children: [
              Expanded(
                child: Text(
                  phoneList.join(' / '),
                  style: TextStyle(
                    fontSize: 12.sp,
                    height: 1.2,
                    fontWeight: FontWeight.w400,
                    color: const Color(0xff495061),
                  ),
                ),
              ),
              AppGaps.hGap10,
              SvgPicture.asset(AppImages.icon_dial, width: 20.w, height: 20.w).clickOnce(() {
                DialingFunction.selectDialingBottomSheet(dataList: phoneList);
              }),
            ],
          ),
          Visibility(
            visible: controller.isShowLeave(),
            child: Container(
              margin: EdgeInsets.only(top: 10.w, bottom: 2.w),
              padding: EdgeInsets.symmetric(vertical: 10.w),
              alignment: Alignment.center,
              decoration: BoxDecoration(
                color: const Color(0xffD4D9FF),
                borderRadius: BorderRadius.all(Radius.circular(45.w)),
              ),
              child: Text(
                '请假',
                style: TextStyle(
                  fontSize: 14.sp,
                  height: 1.2,
                  fontWeight: FontWeight.w400,
                  color: const Color(0xff5C6DFF),
                ),
              ),
            ).clickOnce(() {
              // 跳转到请假页面
              Get.toNamed(AppRoutes.checkInPage, arguments: {'appClockStatus': 3});
            }),
          ),
        ],
      ),
    );
  }

  /// 获取打卡操作
  Widget _getClockIn() {
    // 打卡显示判断
    final String? canCheckIn = controller.canCheckIn();
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Stack(alignment: Alignment.center, children: [
          SvgPicture.asset(
            AppImages.icon_clock_in,
            colorFilter: controller.appClockStatus == -1 ? const ColorFilter.mode(Color(0xffacacaf), BlendMode.srcIn) : null,
          ),
          Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                controller.currentPlan.askForLeave.isEmpty ? canCheckIn ?? '打卡成功' : '已请假',
                style: TextStyle(
                  fontSize: 16.sp,
                  height: 1.2,
                  fontWeight: FontWeight.w500,
                  color: const Color(0xffffffff),
                ),
              ),
              AppGaps.vGap4,
              Text(
                controller.currentTime,
                style: TextStyle(
                  fontSize: 12.sp,
                  height: 1.2,
                  fontWeight: FontWeight.w400,
                  color: const Color(0xffffffff),
                ),
              )
            ],
          )
        ]).clickOnce(controller.clickCheckIn),
        AppGaps.vGap24,
        // Row(
        //   mainAxisAlignment: MainAxisAlignment.center,
        //   children: [
        //     SvgPicture.asset(
        //       AppImages.icon_screen_checkbox,
        //       width: 12.w,
        //       height: 12.w,
        //       colorFilter: const ColorFilter.mode(Color(0xff00CE78), BlendMode.srcIn),
        //     ),
        //     AppGaps.hGap10,
        //   ],
        // )
        Text(controller.getCurrentLocation(),
            style: TextStyle(
              fontSize: 12.sp,
              height: 1.2,
              fontWeight: FontWeight.w400,
              color: const Color(0xff495061),
            )),
      ],
    );
  }
}
